<template>
    <div>
        <!-- label  -->
     <label v-if="label">{{label}}</label>
     <slot></slot>
     <!-- 校验信息提示 -->
     <p v-if="error">{{error}}</p>
     <!-- 校验规则 -->
     <!-- <p>{{form.model}}</p> -->
    </div>
</template>

<script>
import Schema from "async-validator";
export default {
  inject: ["form"],
  props: {
    label: {
      type: String,
      default: ""
    },
    prop: {
      type: String
    }
  },
  data() {
    return {
      error: "" // error 为空说明校验通过
    };
  },
  mounted() {
    //建议在mounted 中进行监听 因为此处可以保证所以孩子都挂载了
    // 事件谁派发谁监听
    this.$on("validate", () => {
      this.validate();
    });
  },
  methods: {
    validate() {
      //规则
      //   console.log(this.from.rules[this.prop]);
      const rules = this.form.rules[this.prop];

      // 当前值
      //   console.log(this.form.model[this.prop]);
      const value = this.form.model[this.prop];
      // 校验描述对象  校验源  校验规则
      const desc = { [this.prop]: rules };

      // 创建Schema 的实例  根据描述创建 Schema
      const schema = new Schema(desc);
      return schema.validate({ [this.prop]: value }, errors => {
        if (errors) {
          console.log(errors);
          this.error = errors[0].message;
          // message 就是我们校验规则的是message
        } else {
          this.error = "";
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
</style>